package com.huaxonline.boot.common.util;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.text.MessageFormat;

public class XmlBeanConvertUtil {

	/**
	 * 写XML
	 * 
	 * @param c
	 * @return
	 * @throws JAXBException
	 */
	public static <T> Marshaller getMarshaller(Class<T> c) throws JAXBException {

		JAXBContext context = JAXBContext.newInstance(c);
		Marshaller marshaller = context.createMarshaller();
		// 编码格式
		marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
		// 是否格式化生成的xml串
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		// 是否省略xml头信息（<?xml version="1.0" encoding="gb2312" standalone="yes"?>）
		marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);

		return marshaller;
	}

	/**
	 * JavaBean转XML
	 * @param t
	 * @return
	 * @throws JAXBException
	 */
	public static <T> String toXML(T t) throws JAXBException {
		Marshaller marshaller = getMarshaller(t.getClass());
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
        marshaller.marshal(t, baos);  
        return baos.toString();
		
	}
	
	
	/**
	 * XML转JavaBean
	 * 
	 * @param clazz
	 * @param context
	 * @return
	 * @throws JAXBException
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T readString(Class<T> clazz, String context) throws JAXBException, IOException {
		try {
			// 获取xml文件内容 context 为文件路径
			// InputStream inputStream =
			// ClassLoader.getSystemRource(context).openStream();

			//context为文件内容串
			InputStream inputStream = new ByteArrayInputStream(context.getBytes());
			JAXBContext jc = JAXBContext.newInstance(clazz);
			Unmarshaller u = jc.createUnmarshaller();
			return (T) u.unmarshal(inputStream);
		} catch (JAXBException e) {
			throw e;
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T readConfig(Class<T> clazz, String config, Object... arguments)
			throws IOException, JAXBException {
		InputStream is = null;
		try {
			if (arguments.length > 0) {
				config = MessageFormat.format(config, arguments);
			}
			JAXBContext jc = JAXBContext.newInstance(clazz);
			Unmarshaller u = jc.createUnmarshaller();
			is = new FileInputStream(config);
			return (T) u.unmarshal(is);
		} catch (IOException e) {
			throw e;
		} catch (JAXBException e) {
			throw e;
		} finally {
			if (is != null) {
				is.close();
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T readConfigFromStream(Class<T> clazz, InputStream dataStream) throws JAXBException {
		try {
			JAXBContext jc = JAXBContext.newInstance(clazz);
			Unmarshaller u = jc.createUnmarshaller();
			return (T) u.unmarshal(dataStream);
		} catch (JAXBException e) {
			throw e;
		}
	}

}
